package main

import (
	"context"
	"fmt"
	"gorm_demo/gen/model"
	"gorm_demo/gen/query"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var QueryObj *query.Query
var DbObj *gorm.DB

func main() {
	ctx := context.Background()
	//初始化数据库连接
	initDb()
	//创建user对象
	//insUser(ctx)
	//查询user对象
	selectUser(ctx)
}

// 查询user对象
func selectUser(ctx context.Context) {
	uQry := QueryObj.User
	uList, err := uQry.WithContext(ctx).Debug().Where(uQry.Gender.Eq(0)).Find()
	//uList, err := QueryObj.User.WithContext(ctx).Debug().Find()
	if err != nil {
		panic(err)
	}
	for _, u := range uList {
		fmt.Println(u)
	}
}

func insUser(ctx context.Context) {
	uName := fmt.Sprintf("user_%d", time.Now().Unix())
	u := &model.User{
		Username: uName,
		Password: "123456",
		Email:    fmt.Sprintf("%s@example.com", uName),
		Phone:    "13800138000",
		Nickname: "张三",
		Gender:   1,
		Birthday: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
		Status:   true,
	}
	//创建user记录
	err := QueryObj.User.WithContext(ctx).Debug().Create(u) //显示sql
	//err := uQry.WithContext(ctx).Create(u)//不显示sql
	if err != nil {
		panic(err)
	}
	fmt.Println("创建成功")
}

func initDb() {
	db, err := gorm.Open(mysql.Open("root:Root2025*@tcp(localhost:3306)/dev_db?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		panic(err)
	}
	//配置连接池
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
	//使用gorm查询构造器
	query.Use(db)
	//将db赋值给全局变量DbObj
	DbObj = db
	//将查询构造器赋值给全局变量QueryObj
	QueryObj = query.Use(DbObj)
}
